<?php

/**
 * UserIdentity represents the data needed to identity a user.
 * It contains the authentication method that checks if the provided
 * data can identity the user.
 */
class Helper
{
	public static function getYesNoList() {
		return array(
			1 => 'Yes',
			0 => 'No',
		);
	}

	public static function getInlineRadioOptions() {
		return array('container'=>'div', 'separator'=>'', 'template'=>'<span class="radio-group">{input} {label}</span>');
	}
	
	public static function getRadioOptions() {
		return array('container'=>'div', 'separator'=>'', 'template'=>'<p>{input} {label}</p>');
	}
	
	/*
	 * Set cookie data
	 *
	 * $area	frontend, backend
	 * $path	abc/def/..
	 */
	public static function setCookie($area, $path, $value) {
		$data = json_decode(Yii::app()->request->cookies[$area], true);
		$tmp = &$data;
		$keys = explode('/', $path);
		foreach($keys as $k) {
			$tmp = &$tmp[$k];
		}
		$tmp = $value;

		Yii::app()->request->cookies[$area] = new CHttpCookie($area, json_encode($data), array(
			'path'=>dirname($_SERVER['PHP_SELF']),
			'expire'=>time()+60*60*24*180,
		));
	}

	public static function getCookie($area, $path='') {
		$data = json_decode(Yii::app()->request->cookies[$area], true);
		$keys = explode('/', $path);
		foreach($keys as $k) {
			if (!isset($data[$k])) return null;
			$data = $data[$k];
		}
		return $data;
	}
	
	public static function forceDownload($file) {
		if (file_exists($file)) {
			header('Content-Description: File Transfer');
			header('Content-Type: application/octet-stream');
			header('Content-Disposition: attachment; filename='.basename($file));
			header('Expires: 0');
			header('Cache-Control: must-revalidate');
			header('Pragma: public');
			header('Content-Length: ' . filesize($file));
			ob_clean();
			flush();
			readfile($file);
			exit;
		}
	}
	
	public static function createSlug($str, $replace=array(), $delimiter='-') {
		setlocale(LC_ALL, 'en_US.UTF8');
		
		if( !empty($replace) ) {
			$str = str_replace((array)$replace, ' ', $str);
		}

		$clean = iconv('UTF-8', 'ASCII//TRANSLIT', $str);
		$clean = preg_replace("/[^a-zA-Z0-9\/_|+ -]/", '', $clean);
		$clean = strtolower(trim($clean, '-'));
		$clean = preg_replace("/[\/_|+ -]+/", $delimiter, $clean);

		return $clean;
	}

	public function parseTime($value) {
		$t = strtotime($value);
		return $t ? date('Y-m-d H:i:s', $t) : '';
	}
}